package com.bluefoxyu.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bluefoxyu.domain.ChatCompletionResponse;
import com.bluefoxyu.domain.CompletionChatParam;
import com.bluefoxyu.domain.DeepSeekRequest;
import com.bluefoxyu.domain.Message;
import com.bluefoxyu.mapper.MessageMapper;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DeepSeekService {

    @Resource
    private OkHttpClient client;
    @Value("${bluefox.deepseek.base_url}")
    private String baseUrl;
    @Value("${bluefox.deepseek.api_key}")
    private String apiKey;

    @Resource
    private MessageMapper messageMapper;

    /**
    * <p>
    * description: 发送用户消息到DeepSeek API。
    * </p>
    *
    * @param userMessage 用户输入的消息字符串
    * @return: java.lang.String API响应的字符串表示形式
    * @author: bluefoxyu
    * @date: 2025-06-25 17:15:21
    */
    public String sendMessage(String userMessage) throws IOException {
        return sendChatCompletion(createDefaultRequest(userMessage));
    }

    /** 
    * <p>
    * description: 创建默认的聊天请求对象，包含系统提示和用户消息。
    * </p>
    *
    * @param userMessage 用户输入的消息字符串
    * @return: com.bluefoxyu.domain.DeepSeekRequest 默认的DeepSeek请求对象
    * @author: bluefoxyu 
    * @date: 2025-06-25 17:18:54 
    */ 
    private DeepSeekRequest createDefaultRequest(String userMessage) {
        DeepSeekRequest request = new DeepSeekRequest();
        request.setMessages(List.of(
                new DeepSeekRequest.Message("assistant", "You are a helpful assistant"),
                new DeepSeekRequest.Message("user", userMessage)
        ));
        return request;
    }

    /** 
    * <p>
    * description: 发送聊天完成请求到DeepSeek API
    * </p>
    *
    * @param request 包含请求数据的对象
    * @return: java.lang.String API响应的字符串表示形式
    * @author: bluefoxyu 
    * @date: 2025-06-25 17:18:26 
    */
    public String sendChatCompletion(DeepSeekRequest request) throws IOException {
        String jsonBody = JSONUtil.toJsonStr(request);
        Request httpRequest = buildRequest(jsonBody);

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException(buildErrorMessage(response));
            }
            // 解析响应体
            String responseBody = Objects.requireNonNull(response.body()).string();
            ChatCompletionResponse chatCompletionResponse = JSONUtil.toBean(responseBody, ChatCompletionResponse.class);

            // 提取第一个choice的消息内容
            if (chatCompletionResponse.getChoices() != null && !chatCompletionResponse.getChoices().isEmpty()) {
                return chatCompletionResponse.getChoices().get(0).getMessage().getContent();
            } else {
                throw new RuntimeException("No valid response from DeepSeek API.");
            }
        }
    }

    /** 
    * <p>
    * description: 根据提供的JSON请求体构建HTTP
    * </p>
    *
    * @param jsonBody JSON格式的请求体字符串
    * @return: okhttp3.Request 构建好的HTTP请求对象
    * @author: bluefoxyu 
    * @date: 2025-06-25 17:19:33 
    */ 
    private Request buildRequest(String jsonBody) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonBody);

        return new Request.Builder()
                .url(baseUrl)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();
    }

    /** 
    * <p>
    * description: 构建错误信息字符串，包含HTTP状态码和响应体内容。
    * </p>
    *
    * @param response HTTP响应对象
    * @return: java.lang.String 错误信息字符串
    * @author: bluefoxyu 
    * @date: 2025-06-25 17:17:40 
    */ 
    private String buildErrorMessage(Response response) throws IOException {
        return String.format("API请求失败: %d - %s",
                response.code(),
                response.body() != null ? response.body().string() : "无响应内容");
    }

    public String chatCompletion(String param) throws IOException {
        // 将传入的参数字符串转换为CompletionChatParam对象
        CompletionChatParam bean = JSONUtil.toBean(param, CompletionChatParam.class);
        String conversationId = bean.getConversation_id();
        String userMessage = bean.getMessage();

        // 查询数据库中的历史消息
        List<Message> historyMessages = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getConversationId, conversationId)
                        .orderByAsc(Message::getId) // 确保按时间顺序排列
        );

        // 构建请求消息列表
        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        for (Message msg : historyMessages) {
            messages.add(new DeepSeekRequest.Message(msg.getUserRole(), msg.getUserContent()));
            messages.add(new DeepSeekRequest.Message(msg.getAssistantRole(), msg.getAssistantContent()));
        }

        // 添加当前用户的提问
        messages.add(new DeepSeekRequest.Message("user", userMessage));

        // 创建请求并发送
        DeepSeekRequest request = new DeepSeekRequest();
        request.setMessages(messages);

        // 发送聊天完成请求到DeepSeek API
        String responseMessage = sendChatCompletion(request);

        // 保存助手的回复到数据库
        Message assistantReply = new Message();
        assistantReply.setUserRole("user");
        assistantReply.setAssistantRole("assistant");
        assistantReply.setUserContent(userMessage); // 用户输入的内容
        assistantReply.setAssistantContent(responseMessage); // 助手的回复内容
        assistantReply.setConversationId(Integer.valueOf(conversationId));
        messageMapper.insert(assistantReply);

        return responseMessage;
    }
}